import prisma from '../lib/prisma';

export class CategoryService {
  // 获取所有分类
  async getAllCategories() {
    return await prisma.articleCategory.findMany({
      where: { status: true },
      orderBy: { sort: 'asc' },
    });
  }

  // 根据ID获取分类
  async getCategoryById(id: number) {
    return await prisma.articleCategory.findUnique({
      where: { id },
    });
  }

  // 创建分类
  async createCategory(data: { name: string; description?: string; sort?: number }) {
    return await prisma.articleCategory.create({
      data: {
        ...data,
        sort: data.sort || 0,
      },
    });
  }

  // 更新分类
  async updateCategory(id: number, data: { name?: string; description?: string; sort?: number; status?: boolean }) {
    return await prisma.articleCategory.update({
      where: { id },
      data,
    });
  }

  // 删除分类
  async deleteCategory(id: number) {
    // 检查是否有文章使用此分类
    const articleCount = await prisma.article.count({
      where: { categoryId: id },
    });

    if (articleCount > 0) {
      throw new Error('该分类下还有文章，无法删除');
    }

    return await prisma.articleCategory.delete({
      where: { id },
    });
  }
} 